// import Vue from 'vue'
import store from 'store';
import router from '../router';
import {OPEN_MASK,SET_HOMEMENU} from 'store/home';
import {USER_SIGNIN} from 'store/user';
import {GIVEUP_MODIFY} from 'store/modifyUser';
import androidUmeng from './androidUmeng';
import iosUmeng from './iosUmeng';
const u = navigator.userAgent;
import share from '../pages/down/index.js';
import {get} from '../api/http';
import {PUSH_URl,UPDATA_URl} from '../store/router';

const comJS = {
    loadUmSDK: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 ? androidUmeng : iosUmeng,
    isIos: function () {
        return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    },
    isAndroid: function () {
        return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
    },
    checkIdNumber: function (idNum) {


        let reg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;

        idNum = this.stringWithNoSpacing(idNum);


        if (reg.test(idNum) === false) {
            return false;
        } else {
            return true;
        }
    },
    checkIsTel: function (phoneNum) {
        if ((/^1[3456789]\d{9}$/.test(parseInt(phoneNum)))) {
            return false;
        } else {
            return true;
        }
    },
    checkIsTelPhone: function(phone){
        var reg =  /(^400[0-9]{7})|(^800[0-9]{7})|(^0[0-9]{2,3}-[0-9]{8})|(^1[3456789]\d{9}$)/;
        if(reg.test(phone)){
            return true;
        } else {
            return false;
        }
    },
    checkBankNumber: function (bankNum) {
        let reg = /^\d{16}|\d{19}$/;
        if (reg.test(bankNum) === false) {
            return false;
        } else {
            return true;
        }
    },
    checkMail: function (mail) {
        let filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (filter.test(mail)) {
            return true;
        }
        else {
            return false;
        }
    },
    stringWithNoSpacing: function (str) {

        let result = str + '';
        if (!this.isEmpty(str)) {
            result = str.replace(/\s/g, '');
        }

        return result;
    },
    //  营业执照编码
    checkEnterpriseCode: function(code){
        var reg = /(^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$)|(^\d{15}$)/;
        if(reg.test(code)){
            return true;
        } else {
            return false;
        }
    },
    isEmpty: function (val) {

        if (typeof val === 'number') {

            return false;
        } else if (typeof val === 'undefined') {
            return true;
        } else if (typeof val === 'boolean') {
            return false;
        } else if (!val) {
            return true;
        } else if (typeof val === 'string') {
            val = val.replace(/\s/g, '');
            return val.length === 0;
        } else if (typeof val === 'object') {
            for (let i in val) {
                if (val.hasOwnProperty(i)) {
                    return false;
                }
            }
            return true;
        }
    },
    checkIsSharePage: function () {
        let href = window.location.href;
        if (href.indexOf('sharePage=1') >= 0) {
            return true;
        } else {
            return false;
        }
    },
    setCookie: function (name, value) {
        localStorage.setItem(name, value);
        /*let Days = day;
        let exp = new Date();
        exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();*/
    },
    getCookie: function (name) {
        return localStorage.getItem(name);
        // let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        // if (arr = document.cookie.match(reg))
        //     return unescape(arr[2]);
        // else
        //     return null;
    },

    //上传图片后转换为服务器需要
    pushImg: function (str) {
        return str.imageUrl;
        // return str.serverId;
    },


    refreshMainTop() {
        if (document.getElementsByClassName('main_allScroll').length > 0) {
            for (let i = 0; i < document.getElementsByClassName('main_allScroll').length; i++) {
                document.getElementsByClassName('main_allScroll')[i].style.top = store.state.interactive.statusBarHeight.height;
            }
        }
        document.getElementsByTagName('body')[0].style.paddingBottom = store.state.interactive.statusBarHeight.tabBarHeight;
    },
    refreshMainTopTwo() {
        if (document.getElementsByClassName('main_allScroll').length > 0) {
            for (let i = 0; i < document.getElementsByClassName('main_allScroll').length; i++) {
                document.getElementsByClassName('main_allScroll')[i].style.top = store.state.interactive.statusBarHeight.height;
            }
        }
        if (document.getElementsByClassName('tabBar').length > 0) {
            document.getElementsByTagName('body')[0].style.paddingBottom = 0;
            document.getElementsByClassName('tabBar')[0].style.paddingBottom = store.state.interactive.statusBarHeight.tabBarHeight;
            document.getElementsByClassName('tabBar')[0].style.height = parseFloat(store.state.interactive.statusBarHeight.tabBarHeight) + 1 + 'rem';
        }
    },
    gotopay(type, data) {  // 1 为微信   2为支付宝
        if (type == 1) {
            Vue.prototype.Interactive.weChatPay(data);
        } else if (type == 2) {
            Vue.prototype.Interactive.alipayPay(data);
        }
    },

    //首页弹框    TODO  接口ok打开
    openMask() {
        /*let style = store.state.homeList.openMask;
        if(style.type == true){
            return ;
        }*/
        /*Vue.$vux.alert.show({
            title:"token",
            content:Vue.prototype.comJS.getCookie('t'),
        })*/
        Vue.prototype.$ajax.ejectActivity()
            .then((res) => {
                var arr = [];
                if (res.body.content && res.body.content != null) {
                    res.body.content.forEach((v) => {
                        v.flag = true;
                        arr.push(v);
                    });
                    store.commit('OPEN_MASK', arr);
                } else {
                    store.commit('OPEN_MASK', arr);
                }
            });
    },


    //  分享链接添加指定query
    addSharePageUrl(url) {
        let el = url.indexOf('&from=App') < 0 ? url : url.substring(url.indexOf('&from=App') + 9) ? url.substring(0, url.indexOf('&from=App')) + url.substring(url.indexOf('&from=App') + 9) : url.substring(0, url.indexOf('&from=App'));
        el = el.indexOf('?from=App') < 0 ? el : el.substring(el.indexOf('?from=App') + 9) ? el.substring(0, el.indexOf('?from=App')) + el.substring(el.indexOf('?from=App') + 9) : el.substring(0, el.indexOf('?from=App'));
        var str = '&inviteCode=' + localStorage.getItem('inviteCode') + '&form=share&sharePage=1';
        if (el.indexOf('&inviteCode') < 0) {
            el = el + str;
        } else {
            el = el.substring(0, el.indexOf('&inviteCode')) + str;
        }
        console.log(el);
        return el;
    },
    //判断QQ微信浏览器

    isWeiXinOrQQ: function () {
        let ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger' || ua.match(/WeiBo/i) == 'weibo') {
            return true;
        } else if (ua.match(/ qq/i) == ' qq' && ua.match(/mqqbrowser/i) == 'mqqbrowser') {
            return true;
        } else if (ua.indexOf('iphone') > -1 || ua.indexOf('mac') > -1) {
            if (ua.indexOf('qq') > -1) {
                return true;
            }

        }
        /*else if (ua.indexOf('qq') > -1) {
            return true;
        } */
        return false;
    },
    isWeixin(){
        let agent = navigator.userAgent.toLowerCase();
        if (agent.match(/MicroMessenger/i) == 'micromessenger') {
            return true;
        } else {
            return false;
        }

    },


    //    打开app
    openApp: function () {
        if (this.isWeiXinOrQQ()) {
            /*打开提示进入浏览器的页面*/
            share(true);
        } else {
            //  TODO 吊起app或者下载app
            //  回到app打开页面辨别方式  sharePage = "1app"
            var url = window.location.href;
            window.location.href = 'shbs://ecosphere.honeybee.com?key=1&url=' + url.slice(0, url.indexOf('&sharePage=1'));
            setTimeout(() => {
                Vue.$vux.alert.show({
                    title: '提示信息',
                    content: '您还没有安装app，去下载',
                    onShow() {
                        console.log('Plugin: I\'m showing');
                    },
                    onHide() {
                        window.location.href = window.location.origin + '/#/down';
                    }
                });
            }, 2000);
        }
    },
    checkFormShare() {
        let url = window.location.href;
        if ((url.indexOf('form=share') > 0 && url.indexOf('sharePage=1') < 0 )|| url.indexOf('from=App') >=0 || url.indexOf('from=app') >=0) {
            return true;
        } else {
            return false;
        }
    },
    checkShareInitAndIsAndroid() {
        if (window.location.href.indexOf('&form=share&sharePage=1') > 0 && this.isAndroid()) {
            if (!this.isWeiXinOrQQ()) {
                var url = window.location.href;
                window.location.href = 'shbs://ecosphere.honeybee.com?key=1&url=' + url.slice(0, url.indexOf('&sharePage=1'));
                setTimeout(() => {
                    Vue.$vux.alert.show({
                        title: '提示信息',
                        content: '您还没有安装app，去下载',
                        onShow() {
                            console.log('Plugin: I\'m showing');
                        },
                        onHide() {
                            window.location.href = window.location.origin + '/#/down';
                        }
                    });
                }, 2000);
            }
        }
    },
    clockerTime: function (num) {
        var time = new Date().getTime();
        var time_sec = Math.floor(time / 1000);
        return this.sec_to_time(time_sec + num);
    },
    sec_to_time: function (time) {
        let s = '';
        s = new Date(time * 1000);
        let year = s.getFullYear();
        let month = s.getMonth() + 1 < 10 ? '0' + (s.getMonth() + 1) : s.getMonth() + 1;
        let data = s.getDate() < 10 ? '0' + s.getDate() : s.getDate();
        let hours = s.getHours() < 10 ? '0' + s.getHours() : s.getHours();
        let minutes = s.getMinutes() < 10 ? '0' + s.getMinutes() : s.getMinutes();
        let second = s.getSeconds() < 10 ? '0' + s.getSeconds() : s.getSeconds();
        return year + '/' + month + '/' + data + ' ' + hours + ':' + minutes + ':' + second;
    },
    updateTime: function (s) {
        var t;
        if (s > -1) {
            var hour = Math.floor(s / 3600);
            var min = Math.floor(s / 60) % 60;
            var sec = s % 60;
            if (hour < 10) {
                t = '0' + hour + ':';
            } else {
                t = hour + ':';
            }

            if (min < 10) {
                t += '0';
            }
            t += min + ':';
            if (sec < 10) {
                t += '0';
            }
            t += sec.toFixed(0);
        }
        return t;
    },
    payMethodscheck: function () {
        return 6;
    },
    payMethodList: function () {
        var a = {key: '6', value: '<span class="balance_s_icon" style="margin-right:0.22rem "></span>余额支付'};
        var b = {key: '1', value: '<span class="wx_s_icon" style="margin-right:0.22rem "></span>微信支付'};
        var c = {key: '2', value: '<span class="alipay_s_icon" style="margin-right:0.22rem "></span>支付宝支付'};
        let arr = this.checkIsNewEdition() ? [a, b, c] : [a, b, c];
        return arr;
    },
    //获取用户信息  用于移动端登录传送token后
    getUserInfo(callback) {
        Vue.prototype.$ajax.inFo.queryIdentityInfo()
            .then((res) => {
                store.commit('USER_SIGNIN', res.body.content);
                if(callback){
                    callback()
                }
            });
    },
    modifyTitle(type) {
        var modifyTitle;
        switch (type) {
        case '1':
            modifyTitle = '更换手机号';
            break;
        case '2':
            modifyTitle = '忘记密码';
            break;
        case '3':
            modifyTitle = '忘记支付密码';
            break;
        case '4':
            modifyTitle = '修改实名信息';
            break;
        default:
            modifyTitle = '更换手机号';
        }
        return modifyTitle;
    },
    modify_clear(){  //  放弃修改申请
        var type = store.state.modifyUser.obj.type;
        if(type == '2'){  //  忘记密码
            Vue.prototype.Interactive.activityWebDismiss();
        } else {
            router.isBack = true;
            router.push({path: '/my/information'});
        }
        store.commit('GIVEUP_MODIFY');
    },
    checkIsNewEdition(){
        if(store.state.interactive.checkIsNewEdition.type){
            return true;
        }else{
            return false;
        }
    },
    closeAlert(){  //  跳转路由时检查弹窗
        if(Vue.$vux.alert.isVisible()){
            Vue.$vux.alert.hide();
        }
        if(Vue.$vux.confirm.isVisible()){
            Vue.$vux.confirm.hide();
        }
    },
    locationToCode(address){
        return get('https://restapi.amap.com/v3/geocode/geo',{
            key: '16be8f6b7c539c551603c654929235dd',
            address: address,
        })
            .then(res => {
                alert(JSON.stringify(res));
                console.log(res.geocodes[0].location);
            })
            .catch(res => {
                return res.data.geocodes[0].location;
            });
    },
    addressToLocationCode(data){
        return get('https://restapi.amap.com/v3/geocode/regeo',{
            key:'16be8f6b7c539c551603c654929235dd',
            location:data
        }).then((res) =>{
            console.log(res);
        })
            .catch((res)=>{
                return res.data.regeocode.addressComponent.district;
            });
    },
    pushPage(data){
        store.commit('PUSH_URl',data);
    },
    undataPage(data){
        store.commit('UPDATA_URl',data);
    },
    getPageComfig(){
        Vue.prototype.$ajax.getPage({environment:null})
            .then((res) => {
                store.commit('SET_HOMEMENU', res.body.content.list);
            });
    },
    deBUG(){
        var debug_url = 'https://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/vconsole/3.0.0/vconsole.min.js';
        var debug_url_script = document.createElement('script');
        var debug_use = document.createElement('script');
        debug_url_script.src = debug_url;
        debug_use.innerHTML = 'setTimeout(()=>new VConsole(), 1000)';
        document.body.appendChild(debug_url_script);
        document.body.appendChild(debug_use);
    },
    cryptoPassword(data){
        const md5Base64 = require('md5-base64');
        return md5Base64(data);
    },
    refreshHead(title) {  //刷新微信头部
        if (this.isIos()) {
            var i = document.createElement('iframe');
            i.src = '../favicon.ico';
            i.style.display = 'none';
            i.onload = function () {
                setTimeout(function () {
                    i.remove();
                }, 9)
            }
            document.title = title;
            document.body.appendChild(i);
        } else {
            document.title = title;
        }

    },


};
// comJS.deBUG()
export default {
    install: function (Vue, option) {
        Vue.prototype.comJS = comJS;
    }
};
export function getRect(el) {
    if (el instanceof window.SVGElement) {
        let rect = el.getBoundingClientRect();
        return {
            top: rect.top,
            left: rect.left,
            width: rect.width,
            height: rect.height
        };
    } else {
        return {
            top: el.offsetTop,
            left: el.offsetLeft,
            width: el.offsetWidth,
            height: el.offsetHeight
        };
    }
}
